<?php
/**
 * @Author: liuhongbin
 * @Email: 514660094@qq.com
 * @Date: 2019-02-12 16:15:10
 * @Description:
 * @LastEditors: liuhongbin
 * @LastEditTime: xxx
 */

namespace addons\cloud_market\controller\api\question;

use addons\cloud_market\controller\api\CloudMarketApiController;
use addons\cloud_market\model\CloudMarketLabel;
use addons\cloud_market\model\CloudMarketQuestion;
use addons\cloud_market\model\CloudMarketQuestionAnswer;
use think\Model;

class Question extends CloudMarketApiController
{
    protected $notApiCheck = ['show', 'list'];
    protected $notApiLogin = ['list', 'show'];

    /**
     * @var CloudMarketQuestion
     */
    protected $model;

    public function initialize()
    {
        parent::initialize();
        $this->model = new CloudMarketQuestion();
    }

    public function list()
    {
        $user = $this->getUser();
        $category = input('category', '');
        $res = $this->model->withoutDefaultOrder()->getPageList(function ($model) use ($category, $user) {
            /**
             * @var \think\Model $model
             */
            if (!isset($user) || $user['id'] == '1') {
                $model->where([['check_switch', '=', '1']]);
            }
            if ($category == 'hot') {
                $model->orderRaw('visits desc');
            } else {
                $model->order('top_switch','desc')->order('id','desc');
            }
            if ($category == 'unsolved') {
                $model->where(['answer_count' => 0]);
            }
            if ($category == 'solved') {
                $model->where([['answer_count', '>', 0]]);
            }
        });
        $data = $res['data'];
        return $this->success($res['count'], $data, $category);
    }

    // 查询
    public function show()
    {
        try {
            $id = input('id');
            $data = $this->model->where('id', $id)->find();
            if (!$data) {
                return $this->error('内容不存在');
            }
            if ($data['check_switch'] == 0 && $data['user_id'] != ($this->userInfo['id'] ?? 0)) {
                return $this->error('当前内容还未审核通过，请耐心等待');
            }
            if ($data['check_switch'] == 1) {
                $data->visits += 1;
                $data->save();
            }
            $data['user'] = array(
                'id'       => $data->user->id,
                'nickname' => $data->user->nickname,
                'avatar'   => $data->user->avatar,
            );
            return $this->success('', $data);
        } catch (\Exception $e) {
            return $this->error($e->getMessage(), ['e' => $e->getLine(), 'l' => $e->getFile()]);
        }

    }

    public function acceptAnswer($id, $answer_id)
    {
        (new CloudMarketQuestionAnswer())->where(['question_id' => $id])->update(['accept_switch' => 0]);
        (new CloudMarketQuestionAnswer())->where(['id' => $answer_id])->update(['accept_switch' => 1]);
        return $this->success('ok');
    }

    public function submit()
    {
        $user = $this->getUser();
        $formData = getFormData();
        // 处理一下label_ids
        if (isset($formData['id'])) {
            if ($formData['user_id'] == $user['id'] || $user['id'] == 1) {
                $question = $this->model->where('id', $formData['id'])->find();
                $formData['label_ids'] = (new CloudMarketLabel())->getLabelIds($formData['label_ids'], $user['id'], 2);
                $formData['content'] = input('post.formData', '', 'htmlspecialchars')['content'] ?? '';
                $data = [
                    'title'     => $formData['title'] ?? '',
                    'content'   => $formData['content'],
                    'classify' => $formData['classify'],
                    'label_ids' => $formData['label_ids'],
                    'addon_id'  => $formData['addon_id']
                ];
                $question->save($data);
                return $this->success('编辑成功', ['id' => $question->id]);
            } else {
                return $this->error('你没有权限修改该问题');
            }
        } else {
            $formData['user_id'] = $user['id'];
            $formData['content'] = input('post.formData', '', 'htmlspecialchars')['content'] ?? '';
            $formData['label_ids'] = (new CloudMarketLabel())->getLabelIds($formData['label_ids'], $user['id'], 2);
            // 先默认为1
            $formData['check_switch'] = 1;
            $this->model->save($formData);
            return $this->success('提交成功', ['id' => $this->model->id]);
        }
    }


    public function del()
    {
        $id = input('id');
        $user = $this->getUser();
        $question = $this->model->where('id', $id)->find();
        if ($question->user_id == $user['id'] || $user['id'] == 1 || in_array('question_del', $user['rule'])) {
            CloudMarketQuestionAnswer::destroy(function ($query) use ($question) {
                $query->where('question_id', '=', $question['id']);
            });
            $question->delete();
            return $this->success('删除成功');
        } else {
            return $this->error('你没有权限删除该问题');
        }
    }

    public function check()
    {
        // TODO 权限控制
        if ($this->userInfo['id'] == 1) {
            // 审核
            $id = input('id', 0);
            $question = CloudMarketQuestion::find($id);
            if ($question) {
                $question->check_swicth = 1;
                $question->save();
                return $this->success('审核成功');
            }
        }
        return $this->error('没有权限审核，审核失败');
    }

}
